window.onload = function () {
    displayConversations();
};

async function fetchChatEvents(promptText, model) {
    const reader = await getFetchReader(promptText, model)
    const decoder = new TextDecoder()
    let events = ""
    document.getElementById('generated-text').value = ''
    const responseElement = document.getElementById('response-section-respone');
    responseElement.innerText = ''
    for (; ;) {
        const { done, value } = await reader.read()
        const decoded = decoder.decode(value)
        try {
            const partial = JSON.parse(decoded.replace(/^[,\[\]\n]*/g, '').replace(/[,\[\]\n]*$/g, ''))
            if (partial.full_update && partial.gen_text.length > 0) {
                responseElement.innerText = partial.gen_text;
            } else {
                responseElement.innerText = responseElement.innerText.trimStart() + partial.gen_text
            }
        } catch (err) {
            console.warn('Not valid json!', decoded, err)
        }
        events += decoded
        if (done) break;
    }
    return events
}

const questionSection = document.getElementById('response-section-question');
const responseSection = document.getElementById('response-section-respone');

async function generate() {
    const textArea = document.getElementById('generated-text');
    const modelSelect = document.getElementById('model-select');
    const promptText = textArea.value;
    const model = modelSelect.value;

    if (!promptText) {
        responseSection.innerHTML = '<p>Please enter a prompt to generate a response.</p>';
        return;
    }

    try {
        const questionElement = document.getElementById('response-section-question');
        questionElement.innerHTML = promptText;

        const events = await fetchChatEvents(promptText, model);
        const data = JSON.parse(events)
        // console.log(data);

        const response = JSON.stringify(data, null, 4);
        const responseText = JSON.parse(response).reduce((acc, curr) => {
            if (curr.full_update && curr.gen_text.length > 0) {
                return curr.gen_text;
            }
            return acc + curr.gen_text
        }, '');
        // responseElement.innerHTML = responseText.trim();
        saveConversation(promptText, response);
        textArea.value = '';
        displayConversations(); // Refresh the sidebar with the new conversation
    } catch (error) {
        console.error('Error when generating response:', error);
        responseSection.innerHTML += `<p>Error when generating response: ${error}</p>`;
    }
}

function saveConversation(prompt, response) {
    const conversation = { prompt, response, timestamp: new Date().toISOString() };
    const conversations = JSON.parse(localStorage.getItem('conversations')) || [];
    conversations.push(conversation);
    localStorage.setItem('conversations', JSON.stringify(conversations));
}

function startNewConversation() {
    document.getElementById('response-section-question').innerHTML = '';
    document.getElementById('response-section-respone').innerHTML = '';
    displayConversations();
}

function displayConversations() {
    const sidebar = document.getElementById('sidebar');
    sidebar.innerHTML = '';
    const conversations = JSON.parse(localStorage.getItem('conversations')) || [];
    conversations.forEach((conversation, index) => {
        const item = document.createElement('div');
        item.title = conversation.prompt;
        item.className = 'history-item';
        const time = new Date(conversation.timestamp).toLocaleString();
        item.innerHTML = `<h4
        >${conversation.prompt}</h4>
        <time datetime=${time}>${time}</time>`;
        item.onclick = () => displayConversationDetails(conversation);
        sidebar.appendChild(item);
    });
}

function displayConversationDetails(conversation) {
    const responseText = JSON.parse(conversation.response).reduce((acc, curr) => {
        if (curr.full_update && curr.gen_text.length > 0) {
            return curr.gen_text;
        }
        return acc + curr.gen_text
    }, '');
    questionSection.innerHTML = conversation.prompt;
    responseSection.innerHTML = responseText.trim();
}